package top.lidee.common.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.lang.Opt;
import cn.hutool.core.util.StrUtil;
import com.alipay.api.domain.BrandBoxDetail;
import com.alipay.api.domain.CategoryVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import jdk.nashorn.internal.ir.IfNode;
import org.springframework.beans.factory.BeanCreationException;
import top.lidee.common.bean.WxPayV3Bean;
import top.lidee.common.dto.StoreDto;
import top.lidee.common.dto.UserInfo;
import top.lidee.common.enums.AdminRoleEnum;
import top.lidee.common.enums.QrCodeEnum;
import top.lidee.common.enums.StatusEnum;
import top.lidee.common.enums.YesOrNoEnum;
import top.lidee.common.service.MerchantService;
import top.lidee.common.service.StoreService;
import top.lidee.common.service.WeixinService;
import top.lidee.common.service.twice.applet.MtStoreCateService;
import top.lidee.common.service.twice.management.*;
import top.lidee.common.service.twice.popularize.PtpBeesInfoService;
import top.lidee.common.util.CommonUtil;
import top.lidee.framework.annoation.OperationServiceLog;
import top.lidee.framework.constant.SupplierInfoConstant;
import top.lidee.framework.enums.CommonExceptionEnum;
import top.lidee.framework.exception.BusinessCheckException;
import top.lidee.framework.pagination.PaginationRequest;
import top.lidee.framework.pagination.PaginationResponse;
import top.lidee.framework.result.GlobalCheck;
import top.lidee.framework.result.PageUtils;
import top.lidee.framework.result.ResponseResult;
import top.lidee.module.backendApi.twice.page.Query;
import top.lidee.repository.bean.StoreDistanceBean;
import top.lidee.repository.mapper.MtStoreMapper;
import top.lidee.repository.mapper.MtUserMapper;
import top.lidee.repository.model.MtMerchant;
import top.lidee.repository.model.MtStore;
import top.lidee.repository.model.twice.pojo.applet.MtStoreCateEntity;
import top.lidee.repository.model.twice.pojo.management.*;
import top.lidee.repository.model.twice.pojo.popularize.PtpBeesInfoEntity;
import top.lidee.repository.model.twice.vo.applet.*;
import top.lidee.repository.model.twice.vo.management.*;
import top.lidee.utils.CopyBean;
import top.lidee.utils.MyCollUtil;
import top.lidee.utils.StringUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.prefs.BackingStoreException;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static top.lidee.framework.constant.AlipayDefaultSettleTypeCon.*;
import static top.lidee.framework.constant.GlobalPattern.IMAGE_URL;
import static top.lidee.framework.constant.SettlementAccountConstant.*;
import static top.lidee.framework.constant.SupplierInfoConstant.WAIT;
import static top.lidee.framework.constant.WechatConstant.*;
import static top.lidee.framework.constant.WechatConstant.ENTERPRISE;
import static top.lidee.framework.constant.WechatConstant.INCOMING_ITEMS_ARE_ABNORMAL;
import static top.lidee.framework.constant.WechatConstant.IN_THE_INCOMING;
import static top.lidee.framework.constant.WechatConstant.SOHO;
import static top.lidee.framework.constant.WechatConstant.THE_INCOMING_REVIEW_IS_COMPLETE;
import static top.lidee.framework.constant.WechatConstant.TO_THE_PUBLIC;
import static top.lidee.framework.enums.CommonExceptionEnum.NOT_PERMISSION;
import static top.lidee.framework.result.GlobalCheck.checkAdmin;
import static top.lidee.framework.result.GlobalCheck.checkMerchantId;
import static top.lidee.utils.CustomIdGenerator.getFifteenAUniqueDigit;
import static top.lidee.utils.MapParamsUtil.getKey;
import static top.lidee.utils.MapParamsUtil.getStatus;

/**
 * 店铺管理业务实现类
 * <p>
 * Created by FSQ
 * CopyRight https://www.lidee.top
 */
@Service
@AllArgsConstructor
public class StoreServiceImpl extends ServiceImpl<MtStoreMapper, MtStore> implements StoreService {

    private MtStoreMapper mtStoreMapper;


    /**
     * 商户接口
     */
    private MerchantService merchantService;

    /**
     * 微信服务接口
     */
    private WeixinService weixinService;

    private final MtUserMapper mtUserMapper;

    private final MtStoreCateService mtStoreCateService;

    private final BmsManagerService bmsManagerService;

    private final PtpBeesInfoService ptpBeesInfoService;

    private final MtUploadCateCertificationLogService mtUploadCateCertificationLogService;
    private final MtSecondaryCateSpecialMapService mtSecondaryCateSpecialMapService;
    private final MtStoreAlipayInputPieceLogService mtStoreAlipayInputPieceLogService;
    private final MtStoreWechatInputPieceLogService mtStoreWechatInputPieceLogService;
    private final TAccountInstIdService tAccountInstIdService;
    private final TpbAliBankAccountService tpbAliBankAccountService;
    private final TpbWechatBankAccountService tpbWechatBankAccountService;

    private final WxPayV3Bean wxPayV3Bean;

    /**
     * 分页查询店铺列表
     *
     * @param paginationRequest
     * @return
     */
    @Override
    public PaginationResponse<StoreDto> queryStoreListByPagination(PaginationRequest paginationRequest, Integer managerId) {
        Page<MtStore> pageHelper = PageHelper.startPage(paginationRequest.getCurrentPage(), paginationRequest.getPageSize());
        LambdaQueryWrapper<MtStore> lambdaQueryWrapper = Wrappers.lambdaQuery();
//        lambdaQueryWrapper.ne(MtStore::getStatus, StatusEnum.DISABLE.getKey());

        String name = paginationRequest.getSearchParams().get("name") == null ? "" : paginationRequest.getSearchParams().get("name").toString();
        if (StringUtils.isNotBlank(name)) {
            lambdaQueryWrapper.like(MtStore::getName, name);
        }
        String status = paginationRequest.getSearchParams().get("status") == null ? "" : paginationRequest.getSearchParams().get("status").toString();
        if (StringUtils.isNotBlank(status)) {
            lambdaQueryWrapper.eq(MtStore::getStatus, status);
        }
        String merchantId = paginationRequest.getSearchParams().get("merchantId") == null ? "" : paginationRequest.getSearchParams().get("merchantId").toString();
        if (StringUtils.isNotBlank(merchantId)) {
            lambdaQueryWrapper.eq(MtStore::getMerchantId, merchantId);
        }
        String storeId = paginationRequest.getSearchParams().get("storeId") == null ? "" : paginationRequest.getSearchParams().get("storeId").toString();
        if (StringUtils.isNotBlank(storeId)) {
            lambdaQueryWrapper.eq(MtStore::getId, storeId);
        }

        //只查询代理商户下的店铺，admin查询所有
        if (!Objects.equals(managerId, 1)) {
            BmsManagerEntity manager = bmsManagerService.getById(managerId);
            Optional.ofNullable(manager).ifPresent(po -> {
                List<String> invitationCodes = Lists.newArrayList();

                List<PtpBeesInfoEntity> ptps = ptpBeesInfoService.list(Wrappers.<PtpBeesInfoEntity>lambdaQuery()
                        .eq(PtpBeesInfoEntity::getManagerId, managerId));
                Optional.ofNullable(ptps).ifPresent(item -> {
                    invitationCodes.addAll(item.stream().map(PtpBeesInfoEntity::getInvitationCode).collect(Collectors.toList()));
                });

                invitationCodes.add(po.getInvitationCode());

                List<MtMerchant> merchants = merchantService.list(Wrappers.<MtMerchant>lambdaQuery()
                        .in(MtMerchant::getInviterNumber, invitationCodes));

                Optional.ofNullable(merchants).ifPresent(item -> {
                    lambdaQueryWrapper.in(MtStore::getMerchantId, item.stream().map(MtMerchant::getId).collect(Collectors.toList()));
                });
            });
        }
        lambdaQueryWrapper.orderByDesc(MtStore::getId);

        lambdaQueryWrapper.orderByAsc(MtStore::getStatus).orderByDesc(MtStore::getIsDefault);
        List<MtStore> storeList = mtStoreMapper.selectList(lambdaQueryWrapper);
        List<StoreDto> dataList = new ArrayList<>();

        for (MtStore mtStore : storeList) {
            StoreDto storeDto = new StoreDto();
            BeanUtils.copyProperties(mtStore, storeDto);
            if (StrUtil.isBlank(storeDto.getName())) {
                storeDto.setName(mtStore.getLicenseName());
            }
            MtMerchant mtMerchant = merchantService.getById(mtStore.getMerchantId());
            if (mtMerchant != null) {
                storeDto.setMerchantName(mtMerchant.getName());
            }
            dataList.add(storeDto);
        }


        PageRequest pageRequest = PageRequest.of(paginationRequest.getCurrentPage(), paginationRequest.getPageSize());
        PageImpl pageImpl = new PageImpl(dataList, pageRequest, pageHelper.getTotal());
        PaginationResponse<StoreDto> paginationResponse = new PaginationResponse(pageImpl, StoreDto.class);
        paginationResponse.setTotalPages(pageHelper.getPages());
        paginationResponse.setTotalElements(pageHelper.getTotal());
        paginationResponse.setContent(dataList);

        return paginationResponse;
    }

    /**
     * 保存店铺信息
     *
     * @param storeDto 店铺信息
     * @return
     * @throws BusinessCheckException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @OperationServiceLog(description = "保存店铺信息")
    public MtStore saveStore(StoreDto storeDto) throws BusinessCheckException {
        MtStore mtStore = new MtStore();

        // 编辑店铺
        if (storeDto.getId() != null) {
            mtStore = queryStoreById(storeDto.getId());
            if (mtStore == null) {
                throw new BusinessCheckException("该店铺不存在");
            }
        }

        mtStore.setName(storeDto.getName());
//        mtStore.setLogo(storeDto.getLogo());
        mtStore.setContact(storeDto.getContact());
        mtStore.setOperator(storeDto.getOperator());
        // if (storeDto.getWxMchId() != null) {
        //     mtStore.setWxMchId(storeDto.getWxMchId());
        // }
        // if (storeDto.getWxApiV2() != null) {
        //     mtStore.setWxApiV2(storeDto.getWxApiV2());
        // }
        // if (storeDto.getWxCertPath() != null) {
        //     mtStore.setWxCertPath(storeDto.getWxCertPath());
        // }
        // if (storeDto.getAlipayAppId() != null) {
        //     mtStore.setAlipayAppId(storeDto.getAlipayAppId());
        // }
        // if (storeDto.getAlipayPrivateKey() != null) {
        //     mtStore.setAlipayPrivateKey(storeDto.getAlipayPrivateKey());
        // }
        // if (storeDto.getAlipayPublicKey() != null) {
        //     mtStore.setAlipayPublicKey(storeDto.getAlipayPublicKey());
        // }
        mtStore.setLicense(storeDto.getLicense());
        mtStore.setCreditCode(storeDto.getCreditCode());
//        mtStore.setBankName(storeDto.getBankName());
//         mtStore.setBankCardName(storeDto.getBankCardName());
//         mtStore.setBankCardNo(storeDto.getBankCardNo());
        mtStore.setUpdateTime(new Date());
        if (storeDto.getId() == null) {
            mtStore.setCreateTime(new Date());
        }
        mtStore.setDescription(storeDto.getDescription());
        mtStore.setPhone(storeDto.getPhone());

        if (storeDto.getIsDefault() != null) {
            if (storeDto.getIsDefault().equals(YesOrNoEnum.YES.getKey())) {
                mtStoreMapper.resetDefaultStore(storeDto.getMerchantId());

            }
        }

        mtStore.setIsDefault(storeDto.getIsDefault());
        mtStore.setAddress(storeDto.getAddress());
        mtStore.setHours(storeDto.getHours());
        mtStore.setLatitude(storeDto.getLatitude());
        mtStore.setLongitude(storeDto.getLongitude());
        mtStore.setStatus(storeDto.getStatus());
        if (storeDto.getMerchantId() != null) {
            mtStore.setMerchantId(storeDto.getMerchantId());
        }

        if (mtStore.getStatus() == null) {
            mtStore.setStatus(StatusEnum.ENABLED.getKey());
        }
        if (mtStore.getId() == null || mtStore.getId() < 1) {
            this.save(mtStore);
        } else {
            mtStoreMapper.updateById(mtStore);
        }

        // 保存二维码
        String page = QrCodeEnum.STORE.getPage() + "?" + QrCodeEnum.STORE.getKey() + "Id=" + mtStore.getId();
        String qr = weixinService.createQrCode(mtStore.getMerchantId(), QrCodeEnum.STORE.getKey(), mtStore.getId(), page, 320);
        mtStore.setQrCode(qr);
        mtStoreMapper.updateById(mtStore);

        return mtStore;
    }

    /**
     * 根据店铺ID获取店铺信息
     *
     * @param id 店铺ID
     * @return
     * @throws BusinessCheckException
     */
    @Override
    public MtStore queryStoreById(Integer id) {
        if (id == null || id < 1) {
            return null;
        }
        return mtStoreMapper.selectById(id);
    }

    /**
     * 获取系统默认店铺
     *
     * @param merchantNo 商户号
     * @return
     */
    @Override
    public MtStore getDefaultStore(String merchantNo) {
        Map<String, Object> params = new HashMap<>();
        params.put("status", StatusEnum.ENABLED.getKey());
        params.put("is_default", YesOrNoEnum.YES.getKey());
        if (StringUtil.isNotEmpty(merchantNo)) {
            MtMerchant mtMerchant = merchantService.queryMerchantByNo(merchantNo);
            if (mtMerchant != null) {
                params.put("merchantId", mtMerchant.getId());
            }
        }
        List<MtStore> storeList = queryStoresByParams(params);
        if (storeList.size() > 0) {
            return storeList.get(0);
        } else {
            Map<String, Object> param = new HashMap<>();
            param.put("status", StatusEnum.ENABLED.getKey());
            List<MtStore> dataList = queryStoresByParams(param);
            if (dataList.size() > 0) {
                return dataList.get(0);
            } else {
                return null;
            }
        }
    }

    /**
     * 根据店铺名称获取店铺信息
     *
     * @param storeName 店铺名称
     * @return
     */
    @Override
    public StoreDto queryStoreByName(String storeName) {
        MtStore mtStore = mtStoreMapper.queryStoreByName(storeName);
        StoreDto storeDto = null;

        if (mtStore != null) {
            storeDto = new StoreDto();
            BeanUtils.copyProperties(mtStore, storeDto);
        }

        return storeDto;
    }

    /**
     * 根据店铺ID获取店铺信息
     *
     * @param id 店铺ID
     * @return
     * @throws BusinessCheckException
     */
    @Override
    public StoreDto queryStoreDtoById(Integer id) throws BusinessCheckException {
        MtStore mtStore = queryStoreById(id);
        if (null == mtStore || StatusEnum.DISABLE.getKey().equals(mtStore.getStatus())) {
            throw new BusinessCheckException("该店铺状态异常");
        }

        StoreDto mtStoreDto = new StoreDto();
        BeanUtils.copyProperties(mtStore, mtStoreDto);

        if (StringUtil.isEmpty(mtStore.getQrCode())) {
            String page = QrCodeEnum.STORE.getPage() + "?" + QrCodeEnum.STORE.getKey() + "Id = " + mtStore.getId();
            String qr = weixinService.createQrCode(mtStore.getMerchantId(), QrCodeEnum.STORE.getKey(), mtStore.getId(), page, 320);
            mtStoreDto.setQrCode(qr);
        }

        return mtStoreDto;
    }

    /**
     * 更新店铺状态
     *
     * @param id       店铺ID
     * @param operator 操作人
     * @param status   状态
     * @return
     * @throws BusinessCheckException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @OperationServiceLog(description = "修改店铺状态")
    public void updateStatus(Integer id, String operator, String status) throws BusinessCheckException {
        MtStore mtStore = queryStoreById(id);
        if (null == mtStore) {
            throw new BusinessCheckException("该店铺不存在.");
        }

        mtStore.setStatus(status);
        mtStore.setUpdateTime(new Date());
        mtStore.setOperator(operator);

        if (Objects.equals(status, "D")) {
            mtStoreMapper.deleteById(mtStore.getId());
        } else {
            mtStoreMapper.updateById(mtStore);
        }

    }

    /**
     * 根据条件查询店铺列表
     *
     * @param params 查询参数
     * @return
     */
    @Override
    public List<MtStore> queryStoresByParams(Map<String, Object> params) {
        LambdaQueryWrapper<MtStore> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.ne(MtStore::getStatus, StatusEnum.DISABLE.getKey());

        String storeId = params.get("storeId") == null ? "" : params.get("storeId").toString();
        if (StringUtils.isNotBlank(storeId)) {
            lambdaQueryWrapper.eq(MtStore::getId, storeId);
        }

        String name = params.get("name") == null ? "" : params.get("name").toString();
        if (StringUtils.isNotBlank(name)) {
            lambdaQueryWrapper.like(MtStore::getName, name);
        }
        String status = params.get("status") == null ? "" : params.get("status").toString();
        if (StringUtils.isNotBlank(status)) {
            lambdaQueryWrapper.eq(MtStore::getStatus, status);
        }
        String merchantId = params.get("merchantId") == null ? "" : params.get("merchantId").toString();
        if (StringUtils.isNotBlank(merchantId)) {
            lambdaQueryWrapper.eq(MtStore::getMerchantId, merchantId);
        }

        lambdaQueryWrapper.orderByAsc(MtStore::getStatus).orderByDesc(MtStore::getIsDefault);
        List<MtStore> dataList = mtStoreMapper.selectList(lambdaQueryWrapper);

        return dataList;
    }

    /**
     * 根据距离远近获取店铺列表
     *
     * @param merchantNo 商户号
     * @param keyword    关键字
     * @param latitude   维度
     * @param longitude  经度
     * @return
     */
    @Override
    public List<MtStore> queryByDistance(String merchantNo, String keyword, String latitude, String longitude) throws BusinessCheckException {
        List<MtStore> dataList = new ArrayList<>();

        MtMerchant mtMerchant = merchantService.queryMerchantByNo(merchantNo);
        Integer merchantId = (mtMerchant == null) ? 0 : mtMerchant.getId();

        List<StoreDistanceBean> distanceList = mtStoreMapper.queryByDistance(merchantId, keyword, latitude, longitude);
        Map<String, Object> param = new HashMap<>();
        param.put("status", StatusEnum.ENABLED.getKey());
        List<MtStore> storeList = mtStoreMapper.selectByMap(param);

        if (distanceList != null) {
            for (StoreDistanceBean bean : distanceList) {
                for (MtStore mtStore : storeList) {
                    if (mtStore.getId().equals(bean.getId())) {
                        // if (StringUtil.isNotEmpty(latitude) && StringUtil.isNotEmpty(longitude)) {
                        //     mtStore.setDistance(new BigDecimal(bean.getDistance()));
                        // } else {
                        //     mtStore.setDistance(new BigDecimal("0.0"));
                        // }
                        dataList.add(mtStore);
                    }
                }
            }
        }

        return dataList;
    }

    /**
     * 获取店铺名称
     *
     * @param storeIds 店铺ID
     * @return
     */
    @Override
    public String getStoreNames(String storeIds) {
        if (StringUtil.isEmpty(storeIds)) {
            return "";
        }
        String[] ids = storeIds.split(",");
        List<String> storeNames = new ArrayList<>();
        if (ids.length > 0) {
            for (int i = 0; i < ids.length; i++) {
                MtStore mtStore = mtStoreMapper.selectById(Integer.parseInt(ids[i]));
                if (mtStore != null) {
                    storeNames.add(mtStore.getName());
                }
            }
        }
        return String.join(",", storeNames);
    }


    /**
     * 校验主营分类
     *
     * @param cateId
     * @param merchantId
     * @return
     */
    private boolean checkStoreCate(Integer cateId, Integer merchantId) {
        //店铺主营分类id必须是二级
        MtStoreCateEntity cate = mtStoreCateService.getById(cateId);
        if (Objects.isNull(cate)) {
            return true;
        } else {
            return !Objects.equals(cate.getCatLevel(), 2);
        }
    }


    @Override
    public PageUtils searchAllStatusInfo(Map<String, Object> params) {

        //法人/店铺名称/手机号码
        String key = getKey(params);
        //0待审核1审核通过2审核未通过
        String status = getStatus(params);

        LambdaQueryWrapper<MtStore> wrapper = Wrappers.<MtStore>lambdaQuery()
                .eq(MtStore::getStatus, status);

        if (StrUtil.isNotBlank(key)) {
            wrapper.like(StrUtil.isNotBlank(key), MtStore::getContact, key)
                    .or(wq -> wq.like(StrUtil.isNotBlank(key), MtStore::getName, key)
                            .or().eq(StrUtil.isNotBlank(key), MtStore::getPhone, key));
        }

        IPage<MtStore> page = this.page(
                new Query<MtStore>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public SearchAllStatusInfoVo searchWaitPass(Integer storeId) {
        MtStore info = this.getOne(Wrappers.<MtStore>lambdaQuery()
                .eq(MtStore::getId, storeId)
                .eq(MtStore::getStatus, WAIT));
        if (!Objects.isNull(info)) {
            return CopyBean.copyBean(info, SearchAllStatusInfoVo.class);
        }
        return null;
    }

    /**
     * @param vo
     * @return top.lidee.framework.result.ResponseResult
     * @description 证照信息第一步校验
     * @author zhangyiheng
     * @date 2024/10/8 19:16
     */
    @Override
    public ResponseResult asliSubjectDataACard(ASLISubjectDataACardVo vo) {


        Pattern r = Pattern.compile(IMAGE_URL);
        //如果主体是个体户或企业则校验营业执照等信息
        if (!StrUtil.equals(vo.getPrincipalType(), SOHO)) {
            //营业执照地址
            if (Objects.isNull(vo.getLicense())) {
                return ResponseResult.errorResult(CommonExceptionEnum.YYZZBNWK);
            } else {
                if (!r.matcher(vo.getLicense()).find()) {
                    return ResponseResult.errorResult(CommonExceptionEnum.YYZZBZQ);
                }
            }

            //统一社会信用代码
            if (Objects.isNull(vo.getCreditCode())) {
                return ResponseResult.errorResult(CommonExceptionEnum.SHTYXYMBNWK);
            }

            //营业执照店铺名称
            if (Objects.isNull(vo.getLicenseName())) {
                return ResponseResult.errorResult(CommonExceptionEnum.YYZZDPMCBNWK);
            }

            //营业执照有效期（开始时间）
            if (Objects.isNull(vo.getLicenseStartTime())) {
                return ResponseResult.errorResult(CommonExceptionEnum.KSSJBNWK);
            }

            //营业执照有效期（结束时间）
            // if (Objects.isNull(vo.getLicenseEndTime())) {
            //     return ResponseResult.errorResult(CommonExceptionEnum.JSSJBNWK);
            // }

            if (Objects.equals(vo.getType(), "0")) {
                //判断是否重复上传
                LambdaQueryWrapper<MtStore> wrapper = Wrappers.<MtStore>lambdaQuery()
                        .eq(MtStore::getLicenseName, vo.getLicenseName())
                        .eq(MtStore::getAddress, vo.getAddress())
                        .eq(MtStore::getIdCard, vo.getIdCard())
                        .eq(MtStore::getCreditCode, vo.getCreditCode());

                int count = this.count(wrapper);

                if (count > 0) {
                    return ResponseResult.errorResult(CommonExceptionEnum.GXXYBZCG);
                }
            }

        } else {

            if (!Objects.isNull(vo.getLicense())) {
                if (!r.matcher(vo.getLicense()).find()) {
                    return ResponseResult.errorResult(CommonExceptionEnum.YYZZBZQ);
                }
            }

            if (Objects.equals(vo.getType(), "0")) {
                LambdaQueryWrapper<MtStore> wrapper = Wrappers.<MtStore>lambdaQuery()
                        .eq(MtStore::getContact, vo.getContact())
                        .eq(MtStore::getAddress, vo.getAddress())
                        .eq(MtStore::getIdCard, vo.getIdCard());

                //营业执照店铺名称
                if (!Objects.isNull(vo.getLicenseName())) {
                    wrapper.eq(MtStore::getLicenseName, vo.getLicenseName());
                }

                //小微/个人判断是否重复上传
                int count = this.count(wrapper);
                if (count > 0) {
                    return ResponseResult.errorResult(CommonExceptionEnum.GXXYBZCG);
                }
            }
        }

        return ResponseResult.ok();
    }


    /**
     * @param vo
     * @return top.lidee.framework.result.ResponseResult
     * @description 证照信息第二步校验
     * 经营资料
     * @author zhangyiheng
     * @date 2024/10/9 08:57
     */
    @Override
    public ResponseResult businessInformationCheck(BusinessInformationCheckVo vo) {

        return ResponseResult.ok();
    }

    /**
     * @param vo
     * @return top.lidee.framework.result.ResponseResult
     * @description 证照信息第三步校验
     * * 结算银行账户
     * @author zhangyiheng
     * @date 2024/10/9 09:05
     */
    @Override
    public ResponseResult settlementBankCheck(SettlementBankCheckVo vo) {

        switch (vo.getType()) {
            case ALI:
                Opt.ofNullable(vo.getTpbAliBankAccount())
                        // .ifPresent(this::alipayCheckBank)
                        .orElseThrow(() -> new BeanCreationException("请填写支付宝结算规则"));
                break;
            case WECHAT:
                String principalType = vo.getPrincipalType();
                Opt.ofNullable(vo.getTpbWechatBankAccount())
                        .ifPresent(wechat -> {
                            wechatpayCheckBank(wechat, principalType);
                        })
                        .orElseThrow(() -> new BeanCreationException("请填写微信结算规则"));

                //校验特约进件超级管理员信息
                Opt.ofNullable(vo.getWxTySuperAdminVo())
                        .ifPresent(this::superAdminCheck)
                        .orElseThrow(BeanCreationException::new, "请填写超级管理员信息");
                break;
            case YIN_LIAN:
            default:
                break;
        }

        return ResponseResult.ok();
    }

    /**
     * @param admin
     * @return void
     * @description 微信 特约商户进件超级管理员校验
     * @author zhangyiheng
     * @date 2024/10/21 15:43
     */
    private void superAdminCheck(WxTySuperAdminVo admin) {
        //超级管理员类型
        Opt.ofNullable(admin.getContactType()).orElseThrow(BeanCreationException::new, "请选择超级管理员类型");
        if (Objects.equals(SUPER, admin.getContactType())) {
            //超级管理员姓名
            Opt.ofBlankAble(admin.getContactName()).orElseThrow(BeanCreationException::new, "请填写超级管理员姓名");
            //超级管理员证件类型
            Opt.ofBlankAble(admin.getContactIdDocType()).orElseThrow(BeanCreationException::new, "请选择超级管理员证件类型");
            //超级管理员身份证件号码
            Opt.ofBlankAble(admin.getContactIdNumber()).orElseThrow(BeanCreationException::new, "请填写超级管理员身份证件号码");
            //超级管理员证件正面照片
            Opt.ofBlankAble(admin.getContactIdDocCopy())
                    .peek(copy -> {
                        Pattern r = Pattern.compile(IMAGE_URL);
                        if (!r.matcher(copy).find()) {
                            throw new BeanCreationException("请上传正确的超级管理员证件正面照片");
                        }
                    })
                    .orElseThrow(BeanCreationException::new, "请上传超级管理员证件正面照片");
            //超级管理员证件反面照片
            Opt.ofBlankAble(admin.getContactIdDocCopyBack())
                    .peek(copyB -> {
                        Pattern r = Pattern.compile(IMAGE_URL);
                        if (!r.matcher(copyB).find()) {
                            throw new BeanCreationException("请上传正确的超级管理员证件反面照片");
                        }
                    })
                    .orElseThrow(BeanCreationException::new, "请上传超级管理员证件反面照片");
            //业务授权函
            Opt.ofBlankAble(admin.getBusinessAuthorizationLetter())
                    .peek(copyB -> {
                        Pattern r = Pattern.compile(IMAGE_URL);
                        if (!r.matcher(copyB).find()) {
                            throw new BeanCreationException("请上传正确的业务授权函照片");
                        }
                    })
                    .orElseThrow(BeanCreationException::new, "请上传业务授权函照片");
            //超级管理员证件有效期开始时间
            Opt.ofNullable(admin.getContactPeriodBegin()).orElseThrow(BeanCreationException::new, "请填写超级管理员证件有效期开始时间");
            //超级管理员证件有效期结束时间
            Opt.ofNullable(admin.getContactPeriodEnd()).orElseThrow(BeanCreationException::new, "请填写超级管理员证件有效期结束时间");
            //超级管理员联系邮箱
            Opt.ofBlankAble(admin.getContactEmail()).orElseThrow(BeanCreationException::new, "请填写超级管理员联系邮箱");
            //超级管理员联系手机
            Opt.ofBlankAble(admin.getMobilePhone()).orElseThrow(BeanCreationException::new, "请填写超级管理员联系手机");
        } else {
            //超级管理员姓名
            Opt.ofBlankAble(admin.getContactName()).orElseThrow(BeanCreationException::new, "请填写超级管理员姓名");
            //超级管理员联系邮箱
            Opt.ofBlankAble(admin.getContactEmail()).orElseThrow(BeanCreationException::new, "请填写超级管理员联系邮箱");
            //超级管理员联系手机
            Opt.ofBlankAble(admin.getMobilePhone()).orElseThrow(BeanCreationException::new, "请填写超级管理员联系手机");
        }
    }


    /**
     * @param ali
     * @return top.lidee.repository.model.twice.pojo.management.TpbAliBankAccountEntity
     * @description 结算银行账户--》支付宝 添加/修改店铺时校验
     * @author zhangyiheng
     * @date 2024/10/18 16:48
     */
    private void alipayCheckBank(TpbAliBankAccountEntity ali) {
        //支付宝有主体限制，小微/个人不允许到银行卡，微信只能到银行卡
        if (StrUtil.isAllBlank(ali.getAlipayNum(), ali.getBankCardNumber())) {
            throw new BeanCreationException(CommonExceptionEnum.YHKZFBZHBNDWK.getMsg());
        }

        //如果选了支付宝账户，银行卡可以不校验，如果选了银行卡，校验银行卡信息
        if (Objects.equals(ali.getAlipayDefaultSettleType(), ALIPAYACCOUNT)) {
            Opt.ofBlankAble(ali.getAlipayNum()).orElseThrow(() -> new BeanCreationException(CommonExceptionEnum.ZFBZHBNWK.getMsg()));
        } else {
            //银行卡类型
            Opt.ofBlankAble(ali.getAccountType()).orElseThrow(() -> new BeanCreationException(CommonExceptionEnum.YHKLXBNWK.getMsg()));

            //银行卡账号使用类型
            Opt.ofBlankAble(ali.getUsageType()).orElseThrow(() -> new BeanCreationException(CommonExceptionEnum.YHKZHSYLX.getMsg()));

            //银行卡账号
            Opt.ofBlankAble(ali.getBankCardNumber()).orElseThrow(() -> new BeanCreationException(CommonExceptionEnum.YHKHBNWK.getMsg()));

            //中国各大银行简码ID
            Opt.ofNullable(ali.getAccountInstId()).orElseThrow(() -> new BeanCreationException(CommonExceptionEnum.YHM.getMsg()));

            //银行卡账户名
            Opt.ofBlankAble(ali.getBankCardHolder()).orElseThrow(() -> new BeanCreationException(CommonExceptionEnum.YHKZHM.getMsg()));

            //开户支行名
            Opt.ofBlankAble(ali.getAccountBranchName()).orElseThrow(() -> new BeanCreationException(CommonExceptionEnum.KHZHM.getMsg()));

            //开户行所在地-省
            Opt.ofBlankAble(ali.getAccountInstProvince()).orElseThrow(() -> new BeanCreationException(CommonExceptionEnum.KHHSZDS.getMsg()));

            //开户行所在地-市
            Opt.ofBlankAble(ali.getAccountInstCity()).orElseThrow(() -> new BeanCreationException(CommonExceptionEnum.KHHSZDSS.getMsg()));
        }

    }

    /**
     * @param
     * @return void
     * @description 结算银行账户--》微信 添加/修改店铺时校验
     * @author zhangyiheng
     * @date 2024/10/18 16:50
     */
    private void wechatpayCheckBank(TpbWechatBankAccountEntity wechat, String principalType) {
        //银行卡类型
        Opt.ofBlankAble(wechat.getAccountType()).orElseThrow(() -> new BeanCreationException(CommonExceptionEnum.YHKLXBNWK.getMsg()));

        //银行卡账号使用类型
        Opt.ofBlankAble(wechat.getUsageType()).orElseThrow(() -> new BeanCreationException(CommonExceptionEnum.YHKZHSYLX.getMsg()));

        //银行卡账号
        Opt.ofBlankAble(wechat.getBankCardNumber()).orElseThrow(() -> new BeanCreationException(CommonExceptionEnum.YHKHBNWK.getMsg()));

        //银行卡账户名
        Opt.ofBlankAble(wechat.getBankCardHolder()).orElseThrow(() -> new BeanCreationException(CommonExceptionEnum.YHKZHM.getMsg()));
        //开户银行
        Opt.ofBlankAble(wechat.getAccountBank()).orElseThrow(() -> new BeanCreationException(CommonExceptionEnum.KHYHBNWK.getMsg()));

        if (Objects.equals("其他银行", wechat.getAccountBank())) {
            //开户支行名
            Opt.ofBlankAble(wechat.getAccountBranchName()).orElseThrow(() -> new BeanCreationException(CommonExceptionEnum.KHZHM.getMsg()));
        }

        //开户行所在地-省
        Opt.ofBlankAble(wechat.getAccountInstProvince()).orElseThrow(() -> new BeanCreationException(CommonExceptionEnum.KHHSZDS.getMsg()));

        //开户行所在地-市
        Opt.ofBlankAble(wechat.getAccountInstCity()).orElseThrow(() -> new BeanCreationException(CommonExceptionEnum.KHHSZDSS.getMsg()));

        //邮箱
        Opt.ofBlankAble(wechat.getEmail()).orElseThrow(() -> new BeanCreationException(CommonExceptionEnum.YXBNWK.getMsg()));


        //除了企业其他的银行卡都只能对私(微信规定，一般只有企业会有对公银行卡)
        if (!Objects.equals(principalType, ENTERPRISE)) {
            if (Objects.equals(wechat.getUsageType(), TO_THE_PUBLIC)) {
                throw new BeanCreationException(CommonExceptionEnum.DQZTBZCDGYHK.getMsg());
            }
        }
    }

    /**
     * @param vo
     * @return top.lidee.framework.result.ResponseResult
     * @description 新增店铺基本信息和证照信息
     * @author zhangyiheng
     * @date 2024/9/24 14:02
     */
    @Override
    @Transactional
    public ResponseResult uploadLicense(AddStoreLicenseInformationVo vo) {
        return saveOrUpdate(vo, null);
    }

    /**
     * @param save   确保店铺id一定是空
     * @param update
     * @return top.lidee.framework.result.ResponseResult
     * @description
     * @author zhangyiheng
     * @date 2024/10/7 17:45
     */
    @Transactional
    public ResponseResult saveOrUpdate(AddStoreLicenseInformationVo save, UpdateByStoreVo update) {

        MtStore store = null;
        List<SpecialQualificationVo> specialQualificationVos = null;
        Integer merchantId = null;
        String oldPrincipalType = null;
        if (!Objects.isNull(save)) {
            merchantId = save.getMerchantId();
            store = CopyBean.copyBean(save, MtStore.class);

            specialQualificationVos = save.getSpecialQualificationVos();

        } else {
            //校验当前用户商户与店铺对应关系
            store = this.getById(update.getStoreId());
            oldPrincipalType = store.getPrincipalType();
            merchantId = update.getMerchantId();
            if (!Objects.equals(store.getMerchantId(), merchantId)) {
                return ResponseResult.errorResult(NOT_PERMISSION);
            }

            BeanUtil.copyProperties(update, store);
            specialQualificationVos = update.getSpecialQualificationVos();


            store.setId(update.getStoreId());
            //如果支付宝或微信有一个审核状态为进件中状态或进件成功则不能修改
            ResponseResult responseResult = null;
            responseResult = checkCanItBeModified(store.getId(), responseResult);
            if (Objects.nonNull(responseResult)) {
                return responseResult;
            }
        }


        //校验主营分类
        if (checkStoreCate(store.getCateId(), merchantId))
            return ResponseResult.errorResult(CommonExceptionEnum.DPFLXZCW);

        //region Description 主题信息、营业执照&身份证校验
        Pattern r = Pattern.compile(IMAGE_URL);
        //如果主体是个体户或企业则校验营业执照等信息
        if (!StrUtil.equals(store.getPrincipalType(), SOHO)) {
            //营业执照地址
            if (Objects.isNull(store.getLicense())) {
                return ResponseResult.errorResult(CommonExceptionEnum.YYZZBNWK);
            } else {
                if (!r.matcher(store.getLicense()).find()) {
                    return ResponseResult.errorResult(CommonExceptionEnum.YYZZBZQ);
                }
            }

            //统一社会信用代码
            if (Objects.isNull(store.getCreditCode())) {
                return ResponseResult.errorResult(CommonExceptionEnum.SHTYXYMBNWK);
            }

            //营业执照店铺名称
            if (Objects.isNull(store.getLicenseName())) {
                return ResponseResult.errorResult(CommonExceptionEnum.YYZZDPMCBNWK);
            }

            //营业执照有效期（开始时间）
            if (Objects.isNull(store.getLicenseStartTime())) {
                return ResponseResult.errorResult(CommonExceptionEnum.KSSJBNWK);
            }

            //营业执照有效期（结束时间）
            // if (Objects.isNull(store.getLicenseEndTime())) {
            //     return ResponseResult.errorResult(CommonExceptionEnum.JSSJBNWK);
            // }

            if (Objects.isNull(update)) {
                //判断是否重复上传
                LambdaQueryWrapper<MtStore> wrapper = Wrappers.<MtStore>lambdaQuery()
                        .eq(MtStore::getLicenseName, store.getLicenseName())
                        .eq(MtStore::getAddress, store.getAddress())
                        .eq(MtStore::getIdCard, store.getIdCard())
                        .eq(MtStore::getCreditCode, store.getCreditCode());
                int count = this.count(wrapper);

                if (count > 0) {
                    return ResponseResult.errorResult(CommonExceptionEnum.GXXYBZCG);
                }
            }

        } else {
            if (!Objects.isNull(store.getLicense())) {
                if (!r.matcher(store.getLicense()).find()) {
                    return ResponseResult.errorResult(CommonExceptionEnum.YYZZBZQ);
                }
            }


            if (Objects.isNull(update)) {
                LambdaQueryWrapper<MtStore> wrapper = Wrappers.<MtStore>lambdaQuery()
                        .eq(MtStore::getContact, store.getContact())
                        .eq(MtStore::getAddress, store.getAddress())
                        .eq(MtStore::getIdCard, store.getIdCard());

                //营业执照店铺名称
                if (!Objects.isNull(store.getLicenseName())) {
                    wrapper.eq(MtStore::getLicenseName, store.getLicenseName());
                } else {
                    wrapper.eq(MtStore::getName, store.getName());
                }
                //小微/个人判断是否重复上传
                int count = this.count(wrapper);
                if (count > 0) {
                    return ResponseResult.errorResult(CommonExceptionEnum.GXXYBZCG);
                }
            }

        }
        //endregion


        //特殊资质在每个进件接口有校验. 默认不合规，待人工审核
        List<MtUploadCateCertificationLogEntity> upload = null;
        if (MyCollUtil.isNotEmpty(specialQualificationVos)) {
            upload = new ArrayList<>();
            for (SpecialQualificationVo specialQualificationVo : specialQualificationVos) {
                MtUploadCateCertificationLogEntity bean = CopyBean.copyBean(specialQualificationVo, MtUploadCateCertificationLogEntity.class);
                bean.setStoreId(store.getId());
                bean.setMerchantId(merchantId);
                bean.setCateId(store.getCateId());
                bean.setIsCompliance("1");
                upload.add(bean);
            }
        }


        store.setMerchantId(merchantId);
        store.setStatus(WAIT);
        store.setExternalId(wxPayV3Bean.getMchId() + "_" + getFifteenAUniqueDigit());

        if (Objects.isNull(save)) {
            //删除特殊资质
            if (MyCollUtil.isNotEmpty(upload)) {
                mtUploadCateCertificationLogService.remove(Wrappers.<MtUploadCateCertificationLogEntity>lambdaQuery()
                        .eq(MtUploadCateCertificationLogEntity::getStoreId, store.getId()));
            }

            //如果主体类型和旧主体类型不一样 则判断如果此店铺存在结算信息，则修改审核状态
            if (StrUtil.isNotBlank(store.getPrincipalType())) {
                if (!Objects.equals(store.getPrincipalType(), oldPrincipalType)) {
                    tpbWechatBankAccountService.update(Wrappers.<TpbWechatBankAccountEntity>lambdaUpdate()
                            .set(TpbWechatBankAccountEntity::getStatus, "0")
                            .eq(TpbWechatBankAccountEntity::getStoreId, store.getId()));

                    tpbAliBankAccountService.update(Wrappers.<TpbAliBankAccountEntity>lambdaUpdate()
                            .set(TpbAliBankAccountEntity::getStatus, "0")
                            .eq(TpbAliBankAccountEntity::getStoreId, store.getId()));
                }
            }
        }
        //店铺
        this.saveOrUpdate(store, Wrappers.<MtStore>lambdaUpdate()
                .eq(MtStore::getId, store.getId()));
        Integer storeId = store.getId();
        //特殊资质
        Optional.ofNullable(upload).ifPresent(item -> {
            item.forEach(po -> po.setStoreId(storeId));
            mtUploadCateCertificationLogService.saveBatch(item);
        });

        return ResponseResult.ok();
    }

    private ResponseResult checkCanItBeModified(Integer storeId, ResponseResult responseResult) {
        //如果支付宝或微信有一个审核状态为进件中状态或进件成功则不能修改
        MtStoreAlipayInputPieceLogEntity aliPieceLog = mtStoreAlipayInputPieceLogService.getOne(Wrappers.<MtStoreAlipayInputPieceLogEntity>lambdaQuery()
                .eq(MtStoreAlipayInputPieceLogEntity::getStoreId, storeId)
                .in(MtStoreAlipayInputPieceLogEntity::getState, IN_THE_INCOMING, THE_INCOMING_REVIEW_IS_COMPLETE));
        if (Objects.nonNull(aliPieceLog)) {
            responseResult = ResponseResult.errorResult(CommonExceptionEnum.CDPYJJZFBCG);
        }
        MtStoreWechatInputPieceLogEntity wechatPieceLog = mtStoreWechatInputPieceLogService.getOne(Wrappers.<MtStoreWechatInputPieceLogEntity>lambdaQuery()
                .eq(MtStoreWechatInputPieceLogEntity::getStoreId, storeId)
                .in(MtStoreWechatInputPieceLogEntity::getState, IN_THE_INCOMING, THE_INCOMING_REVIEW_IS_COMPLETE));
        if (Objects.nonNull(wechatPieceLog)) {
            responseResult = ResponseResult.errorResult(CommonExceptionEnum.CDPYJJWXCG);
        }
        return responseResult;
    }

    /**
     * @param storeId
     * @param merchantId
     * @return top.lidee.framework.result.ResponseResult
     * @description 根据id查询当前店铺可以修改的信息
     * @author zhangyiheng
     * @date 2024/9/27 01:07
     */
    @Override
    public ResponseResult getStoreLicenseInformationById(Integer storeId, Integer merchantId, String type) {


        MtStore store = this.getById(storeId);

        if (!Objects.equals(store.getMerchantId(), merchantId)) {
            return ResponseResult.errorResult(NOT_PERMISSION);
        }

        //如果支付宝或微信有一个审核状态为进件中状态或进件成功则不能修改
        ResponseResult responseResult = null;
        responseResult = checkCanItBeModified(store.getId(), responseResult);
        if (Objects.nonNull(responseResult)) {
            return responseResult;
        }

        AddStoreLicenseInformationVo vo = CopyBean.copyBean(store, AddStoreLicenseInformationVo.class);


        //回显当前店铺的特殊资质照片url集合
        List<MtUploadCateCertificationLogEntity> logs = mtUploadCateCertificationLogService.list(Wrappers.<MtUploadCateCertificationLogEntity>lambdaQuery()
                .eq(MtUploadCateCertificationLogEntity::getStoreId, store.getId()));

        if (MyCollUtil.isNotEmpty(logs)) {
            vo.setSpecialQualificationVos(CopyBean.copyBeanList(logs, SpecialQualificationVo.class));
        }

        switch (type) {
            case ALI:
                TpbAliBankAccountEntity tpbAliBankAccount = tpbAliBankAccountService.getOne(Wrappers.<TpbAliBankAccountEntity>lambdaQuery()
                        .eq(TpbAliBankAccountEntity::getStoreId, store.getId()));
                Opt.ofNullable(tpbAliBankAccount).ifPresent(vo::setTpbAliBankAccount);
                break;
            case WECHAT:
                TpbWechatBankAccountEntity tpbWechatBankAccount = tpbWechatBankAccountService.getOne(Wrappers.<TpbWechatBankAccountEntity>lambdaQuery()
                        .eq(TpbWechatBankAccountEntity::getStoreId, store.getId()));
                Opt.ofNullable(tpbWechatBankAccount).ifPresent(vo::setTpbWechatBankAccount);

                //超级管理员
                MtStoreWechatInputPieceLogEntity pieceLog = mtStoreWechatInputPieceLogService.getOne(Wrappers.<MtStoreWechatInputPieceLogEntity>lambdaQuery()
                        .eq(MtStoreWechatInputPieceLogEntity::getStoreId, store.getId())
                        .or(wq -> wq.isNull(MtStoreWechatInputPieceLogEntity::getState).eq(MtStoreWechatInputPieceLogEntity::getState, INCOMING_ITEMS_ARE_ABNORMAL)));
                Opt.ofNullable(pieceLog).ifPresent(log -> {
                    WxTySuperAdminVo wxTySuperAdminVo = CopyBean.copyBean(log, WxTySuperAdminVo.class);
                    vo.setWxTySuperAdminVo(wxTySuperAdminVo);
                });
                break;
            default:
                break;
        }


        return ResponseResult.okResult(vo);
    }


    /**
     * @param vo
     * @param
     * @return top.lidee.framework.result.ResponseResult
     * @description 根据id修改当前店铺 如果支付宝或微信有一个审核状态为进件中状态或进件成功则不能修改，如果为人工审核成功状态则重新纳入审核状态
     * @author zhangyiheng
     * @date 2024/9/27 09:40
     */
    @Override
    @Transactional
    public ResponseResult updateByStore(UpdateByStoreVo vo) {
        return saveOrUpdate(null, vo);
    }


    /**
     * @param
     * @param principalType
     * @param cateId
     * @return top.lidee.framework.result.ResponseResult
     * @description 1.描述：根据选中的分类并且需要特殊资质时，查询出需要哪些特殊资质图片，至少传一张
     * * 2.入参：
     * *  1）选中的主体类型值0个体户，1企业，2小微/个人（用于微信主体类型（哪个主体类型店铺必须传,至少传一张））
     * *  2）选中的二级类目id
     * @author zhangyiheng
     * @date 2024/10/7 20:16
     */
    @Override
    public ResponseResult getSpecialMapByTypeACateId(String principalType, Integer cateId) {


        GetSpecialMapByTypeACateIdVo vo = new GetSpecialMapByTypeACateIdVo();

        List<MtSecondaryCateSpecialMapEntity> map = mtSecondaryCateSpecialMapService.list(Wrappers.<MtSecondaryCateSpecialMapEntity>lambdaQuery()
                .eq(MtSecondaryCateSpecialMapEntity::getCateId, cateId));

        List<String> types = map.stream().map(MtSecondaryCateSpecialMapEntity::getWechatSubjectType).collect(Collectors.toList());
        if (MyCollUtil.isNotEmpty(types) && types.get(0).contains(principalType)) {
            vo.setIsMust("0");
        } else {
            vo.setIsMust("1");
        }

        vo.setVos(map);

        return ResponseResult.okResult(vo);
    }

    /**
     * @param
     * @return top.lidee.framework.result.ResponseResult
     * @description 中国各大银行集合
     * @author zhangyiheng
     * @date 2024/10/7 20:50
     */
    @Override
    public ResponseResult getRedliningList() {
        return ResponseResult.okResult(tAccountInstIdService.list());
    }

    /**
     * @param vo
     * @param merchantId
     * @return top.lidee.framework.result.ResponseResult
     * @description 新增店铺基本信息
     * @author zhangyiheng
     * @date 2024/10/11 13:40
     */
    @Override
    @Transactional
    public ResponseResult addStoreBasicInformation(AddStoreBasicInformationVo vo, Integer merchantId) {

        MtStore store = CopyBean.copyBean(vo, MtStore.class);
        store.setMerchantId(merchantId);

        //如果主体不是小微/个体 校验营业执照
        Pattern r = Pattern.compile(IMAGE_URL);
        //如果主体是个体户或企业则校验营业执照等信息
        if (!StrUtil.equals(store.getPrincipalType(), SOHO)) {
            //营业执照地址
            if (Objects.isNull(store.getLicense())) {
                return ResponseResult.errorResult(CommonExceptionEnum.YYZZBNWK);
            } else {
                if (!r.matcher(store.getLicense()).find()) {
                    return ResponseResult.errorResult(CommonExceptionEnum.YYZZBZQ);
                }
            }

            //统一社会信用代码
            if (Objects.isNull(store.getCreditCode())) {
                return ResponseResult.errorResult(CommonExceptionEnum.SHTYXYMBNWK);
            }

            //营业执照店铺名称
            if (Objects.isNull(store.getLicenseName())) {
                return ResponseResult.errorResult(CommonExceptionEnum.YYZZDPMCBNWK);
            }


            //营业执照有效期（开始时间）
            if (Objects.isNull(store.getLicenseStartTime())) {
                return ResponseResult.errorResult(CommonExceptionEnum.KSSJBNWK);
            }

            //营业执照有效期（结束时间）
            if (Objects.isNull(store.getLicenseEndTime())) {
                return ResponseResult.errorResult(CommonExceptionEnum.JSSJBNWK);
            }

            //判断是否重复上传
            LambdaQueryWrapper<MtStore> wrapper = Wrappers.<MtStore>lambdaQuery()
                    .eq(MtStore::getLicenseName, store.getLicenseName())
                    .eq(MtStore::getAddress, store.getAddress())
                    .eq(MtStore::getIdCard, store.getIdCard())
                    .eq(MtStore::getCreditCode, store.getCreditCode());
            int count = this.count(wrapper);

            if (count > 0) {
                return ResponseResult.errorResult(CommonExceptionEnum.GXXYBZCG);
            }

        } else {
            LambdaQueryWrapper<MtStore> wrapper = null;
            //如果填写了校验相关信息
            if (!Objects.isNull(store.getLicense())) {
                if (!r.matcher(store.getLicense()).find()) {
                    return ResponseResult.errorResult(CommonExceptionEnum.YYZZBZQ);
                }
                //统一社会信用代码
                if (Objects.isNull(store.getCreditCode())) {
                    return ResponseResult.errorResult(CommonExceptionEnum.SHTYXYMBNWK);
                }

                //营业执照店铺名称
                if (Objects.isNull(store.getLicenseName())) {
                    return ResponseResult.errorResult(CommonExceptionEnum.YYZZDPMCBNWK);
                }

                //营业执照有效期（开始时间）
                if (Objects.isNull(store.getLicenseStartTime())) {
                    return ResponseResult.errorResult(CommonExceptionEnum.KSSJBNWK);
                }

                //营业执照有效期（结束时间）
                if (Objects.isNull(store.getLicenseEndTime())) {
                    return ResponseResult.errorResult(CommonExceptionEnum.JSSJBNWK);
                }

                //判断是否重复上传
                wrapper = Wrappers.<MtStore>lambdaQuery()
                        .eq(MtStore::getName, store.getName())
                        .eq(MtStore::getAddress, store.getAddress())
                        .eq(MtStore::getIdCard, store.getIdCard())
                        .eq(MtStore::getCreditCode, store.getCreditCode());

            } else {
                store.setName(vo.getLicenseName());
                wrapper = Wrappers.<MtStore>lambdaQuery()
                        .eq(MtStore::getContact, store.getContact())
                        .eq(MtStore::getAddress, store.getAddress())
                        .eq(MtStore::getIdCard, store.getIdCard())
                        .eq(MtStore::getName, store.getName());
            }


            //小微/个人判断是否重复上传
            int count = this.count(wrapper);
            if (count > 0) {
                return ResponseResult.errorResult(CommonExceptionEnum.GXXYBZCG);
            }

        }

        this.save(store);

        return ResponseResult.ok();
    }


    /**
     * @param vo
     * @return top.lidee.framework.result.ResponseResult
     * @description 增加当前店铺的结算银行账户信息
     * @author zhangyiheng
     * @date 2024/10/21 15:12
     */
    @Override
    @Transactional
    public ResponseResult saveSettlementAccount(SettlementBankCheckVo vo) {

        //region Description 结算银行账户校验
        ResponseResult responseResult = settlementBankCheck(vo);
        if (!Objects.equals(responseResult.getCode(), 0)) {
            return responseResult;
        }
        //endregion

        //如果支付宝或微信有一个审核状态为进件中状态或进件成功则不能修改
        responseResult = checkCanItBeModified(vo.getStoreId(), responseResult);
        if (!Objects.equals(responseResult.getCode(), 0)) {
            return responseResult;
        }

        //保存
        switch (vo.getType()) {
            case ALI:
                TpbAliBankAccountEntity tpbAliBankAccount = vo.getTpbAliBankAccount();
                Opt.ofNullable(tpbAliBankAccount).ifPresent(ali -> {
                    ali.setStoreId(vo.getStoreId());
                    ali.setStatus("0");
                    tpbAliBankAccountService.saveOrUpdate(ali);
                });
                break;
            case WECHAT:
                //超级管理员
                WxTySuperAdminVo wxTySuperAdminVo = vo.getWxTySuperAdminVo();
                Opt.ofNullable(wxTySuperAdminVo).ifPresent(admin -> {
                    MtStoreWechatInputPieceLogEntity pieceLog = CopyBean.copyBean(wxTySuperAdminVo, MtStoreWechatInputPieceLogEntity.class);
                    pieceLog.setStoreId(vo.getStoreId());
                    pieceLog.setState("");
                    mtStoreWechatInputPieceLogService.saveOrUpdate(pieceLog);
                });

                TpbWechatBankAccountEntity tpbWechatBankAccount = vo.getTpbWechatBankAccount();
                Opt.ofNullable(tpbWechatBankAccount).ifPresent(wechat -> {
                    wechat.setStoreId(vo.getStoreId());
                    wechat.setStatus("0");
                    tpbWechatBankAccountService.saveOrUpdate(wechat);
                });
                break;
            default:
                break;
        }

        return ResponseResult.ok();
    }

}
